<template>
  <div class="pageWrapper">
    <SearchBar @onSearch="handleSearch" @childFn="resetForm">
      <SearchBarItem label="清分日期：" :labelLg="8">
        <DatePicker
          type="daterange"
          class="timeWidth"
          ref="settleDatePicker"
          transfer
          split-panels
          placeholder="请选择"
          @on-change="settleDate"
        ></DatePicker>
      </SearchBarItem>
    </SearchBar>

    <RemoteTable
      ref="remoteTable"
      :namespace="namespace"
      :columns="columns"
      :selected="selectedData"
      :isFixedHeader="true"
      @onSelectionChange="selectList"
    >
      <template #extra>
        <Authc permissions="trade:settlement:bill:UnionPayBill:export">
          <Row :gutter="16">
            <Col span="10">
              <Select :clearable="true" :filterable="true" v-model="choiceMerchant" placeholder="请选择商户">
                <Option
                  :value="item.value"
                  v-for="(item, value) in merchantList"
                  :key="value"
                >{{ item.label }}</Option
                >
              </Select>
            </Col>
            <Col span="8">
              <Button :loading="exportLoading" type="primary" icon="ios-download-outline" @click="exportExcelMultiple">按日期分别导出</Button>
            </Col>
            <Col span="5">
              <Button :loading="exportLoading" type="primary" icon="ios-download-outline" @click="exportExcel">合并导出</Button>
            </Col>
          </Row>
        </Authc>
      </template>
    </RemoteTable>


    <Modal
      v-model="selectMerchantModal"
      title="选择商户导出"
      :loading="modalLoading"
      @on-ok="submitExportMerchant"
      @on-cancel="closeMerchantModal">
      <Form ref="merchantModal" :model="selectedMerchant" :rules="ruleValidate" :label-width="80">
        <FormItem label="商户" prop="merchantCode">
          <Select :clearable="true" :filterable="true" v-model="selectedMerchant.merchantCode" placeholder="请选择商户">
            <Option
              :value="item.value"
              v-for="(item, value) in merchantList"
              :key="value"
            >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import {Input, DatePicker, Button, Message} from "view-design";
import SearchBar from "@/components/SearchBar";
import RemoteTable from "@/components/RemoteTable";
import {namespace} from "../Module/unionPayBillModule";
import util from "@/utils/util";
import Authc from "@/components/Authc";
import {getMerchantAllMerchant, getMerchantAndMerchantPayChannel} from '@/api/statement';

export default {
  name: "tables_page",
  components: {
    Input,
    Button,
    DatePicker,
    RemoteTable,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    Message,
    Authc
  },
  data() {
    return {
      namespace: namespace,
      exportText: "导出选中",
      exportLoading: false,
      searchModule: {
        data: [],
        id: [],
      },
      modalLoading: false,
      // 选择商户
      selectMerchantModal: false,
      // 商户列表
      merchantList: [],
      //商户选中
      selectedMerchant: {
        merchantCode: '',
      },
      selectedData: [],
      choiceMerchant:'',// 选中的商户
      ruleValidate: {
        merchantCode: [
          {required: true, message: '请选择商户', trigger: 'change'}
        ],
      },
      columns: [
        {
          type: "selection",
          align: "center",
          minWidth: 55,
          fixed: "left"
        },
        {
          title: "序号",
          type: "index",
          align: "center",
          width: 80,
        },
        {
          title: "清分ID",
          key: "id",
          align: "center",
          minWidth: 220,
          fixed: "left"
        },
        {
          title: "清分日期",
          key: "settleDate",
          align: "center",
          minWidth: 150,
        },
        {
          title: "清分商户数",
          key: "settleMerchantCount",
          align: "center",
          width: 80,
        },
        {
          title: "应清分金额(元)",
          key: "settleAmount",
          align: "center",
          minWidth: 130,
          render: (h, params) => {
            let item = params.row.settleAmount / 100;
            return h("span", util.toMoney(item));
          },
        },
        {
          title: "实际清分金额(元)",
          key: "settleSuccesAmount",
          align: "center",
          minWidth: 130,
          render: (h, params) => {
            let item = params.row.settleSuccesAmount / 100;
            return h("span", util.toMoney(item));
          },
        },
        {
          title: "应划付金额(元)",
          key: "apprAmount",
          align: "center",
          minWidth: 130,
          render: (h, params) => {
            let item = params.row.apprAmount / 100;
            return h("span", util.toMoney(item));
          },
        },
        {
          title: "退款金额(元)",
          key: "apprRefund",
          align: "center",
          minWidth: 130,
          render: (h, params) => {
            let item = params.row.apprRefund / 100;
            return h("span", util.toMoney(item));
          },
        },
        {
          title: "实际划付金额(元)",
          key: "apprSuccessAmount",
          align: "center",
          minWidth: 130,
          render: (h, params) => {
            let item = params.row.apprSuccessAmount / 100;
            return h("span", util.toMoney(item));
          },
        },
        {
          title: "应抽佣金额(元)",
          key: "distAmount",
          align: "center",
          minWidth: 130,
          render: (h, params) => {
            let item = params.row.distAmount / 100;
            return h("span", util.toMoney(item));
          },
        },
        {
          title: "退款返还抽佣金额(元)",
          key: "refundDistAmount",
          align: "center",
          minWidth: 130,
          render: (h, params) => {
            let item = params.row.refundDistAmount / 100;
            return h("span", util.toMoney(item));
          },
        },
        {
          title: "实际抽佣金额(元)",
          key: "distSuccessAmount",
          align: "center",
          minWidth: 130,
          render: (h, params) => {
            let item = params.row.distSuccessAmount / 100;
            return h("span", util.toMoney(item));
          },
        },
        {
          title: "操作",
          key: "action",
          // fixed: "right",
          align: "center",
          minWidth: 150,
          permission: 'trade:settlement:bill:UnionPayBill',
          render: (h, data) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.exportByMerchant(data.row)
                  }
                }
              }, '按商户导出'),
            ]);
          }
        }
      ],
    };
  },
  created() {
    this.queryMerchant()
  },
  methods: {
    // 清空事件；
    resetForm() {
      // 清空时间选择
      this.$refs["settleDatePicker"].handleClear();
    },
    async queryMerchant() {
      // 查询商户
      const merchantList = await getMerchantAllMerchant();
      const selectMerchantList = merchantList.map(({merchantCode, merchantName}) => {
        return {
          value: merchantCode,
          label: merchantName
        };
      });
      this.merchantList = selectMerchantList
    },
    settleDate(date, type) {
      this.searchModule.settleDateStart = date ? date[0] : "";
      this.searchModule.settleDateEnd = date ? date[1] : "";
    },
    handleSearch() {
      let pageSize = {
        currentPage: 1,
        pageSize: 10,
      };
      this.$store.dispatch(`${namespace}/query`, {
        ...this.searchModule,
        ...pageSize,
      });
    },
    selectList(data) {
      this.selectedData = data;
    },
    // 打开商户导出弹窗
    exportByMerchant(row) {
      let tables = this.$refs.remoteTable.getTables();
      tables.selectAll(false)
      this.selectedData = [row];
      this.selectMerchantModal = true
    },
    // 确认导出
    async submitExportMerchant() {
      let self = this
      self.modalLoading = true
      this.$refs['merchantModal'].validate(async valid => {
        if (valid) {
          await self.exportExcel()
          self.closeMerchantModal()
        } else {
          self.$Message.error("请选择商户！")
          self.closeMerchantModal()
        }
      });
    },
    // 关闭商户导出弹窗
    closeMerchantModal() {
      this.selectedData = [];
      this.selectMerchantModal = false
      this.modalLoading = false
      this.selectedMerchant = {
        merchantCode: ''
      }
    },
    // 按日期导出多个文件
    async exportExcelMultiple(){
      await this.exportExcel(1)
    },
    async exportExcel(isMultipleFile) {
      this.$data.exportLoading = true;
      let ids = this.selectedData.map((item) => {
        return item.id
      });
      if (ids.length == 0) {
        this.$Message.warning('请至少选择一条数据导出');
        this.$data.exportLoading = false;
        return;
      }
      // id数量为1时导出excel，否则是zip
      const fileType = isMultipleFile&&isMultipleFile == 1 ?"zip"  : null
      const self=this
      try {
        let payload = {id: ids,is_merge:isMultipleFile&&isMultipleFile == 1?0:1}
        if (self.selectedMerchant.merchantCode) {
          payload['merchantCode'] = self.selectedMerchant.merchantCode
        } else if(self.choiceMerchant){
          payload['merchantCode'] = self.choiceMerchant
        }
        let res = await self.$store.dispatch(`${namespace}/exportExcel`, payload);
        if(self.selectedMerchant.merchantCode){
          // 导出一个文件
          const merchantId=ids[0]
          const current_merchant=self.merchantList.filter(item=>item.value===self.selectedMerchant.merchantCode)

        

          util.doExportExcle(res, 'application/vnd.ms-excel', `${current_merchant[0].label}-${self.selectedData[0].settleDate}`,'xlsx');
          return
        }
        util.exportExcle(res, "银联清分信息表", fileType);
      } catch (error) {
        console.log(error)
        this.$Message.error({content: "导出失败"});
      } finally {
        this.$data.exportLoading = false;
      }
    },
  },
  async mounted() {
    setTimeout(() => {
      this.loading = false;
    }, 1000);
  },
};
</script>

<style>
</style>
